const { app, BrowserWindow, Menu } = require('electron');
const { getInventory, sendPrice } = require('./client/server');
const path = require('path');
const isDev = process.env.NODE_ENV === 'development';

// 添加热更新
if (isDev) {
  try {
    require('electron-reloader')(module, {
      debug: true,
      watchRenderer: true
    });
  } catch (_) { console.log('Error'); }
}

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: true,
      webSecurity: true,
      allowRunningInsecureContent: false
    }
  });

  // 创建菜单模板
  const template = [
    {
      label: '库存管理',
      submenu: [
        {
          label: '获取库存',
          click: () => {
            console.log('获取库存1');
            getInventory().then(res => {
              console.log(res);
            });
          }
        },
        {
          label: '报价',
          click: () => {
            console.log('报价1');
            sendPrice().then(res => {
              console.log(res);
            });
          }
        }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

  // 在开发环境中加载 React 开发服务器
  if (isDev) {
    mainWindow.loadURL('https://steamcommunity.com/');
    mainWindow.webContents.openDevTools();
  } else {
    // 在生产环境中加载打包后的 React 应用
    mainWindow.loadFile(path.join(__dirname, 'build', 'index.html'));
  }

  // 设置 CSP (Content Security Policy)
  // mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
  //   callback({
  //     responseHeaders: {
  //       ...details.responseHeaders,
  //       'Content-Security-Policy': [
  //         "default-src '*'",
  //         "script-src '*'",
  //         "style-src '*' 'unsafe-inline'",
  //         "img-src '*' data: https:",
  //         "connect-src '*' https:"
  //       ].join('; ')
  //     }
  //   });
  // });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});